<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use DB;

class CalculateUsersOrdersNum extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'book-shop:calculate-users-orders-num';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '检测用户买书卖书数量';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->info("开始获取...");

        $users = DB::table('users')->where('user_type',1)->get();
        if($users->isNotEmpty())
        {
            foreach ($users as $v)
            {
                $buy_orders_num = DB::table('orders')->where('user_id',$v->id)->where('state','>',1)->count();
                $sell_orders_num = DB::table('sell_orders')->where('user_id',$v->id)->where('state','>',2)->count();

                $update_data = [
                    'buy_orders_num'    => $buy_orders_num,
                    'sell_orders_num'   => $sell_orders_num
                ];
                if($buy_orders_num > 0 || $sell_orders_num > 0)
                {
                    //下过单 不管买书还是卖书
                    $update_data['is_order'] = 1;
                }
                DB::table('users')->where('id',$v->id)->update($update_data);
            }

        }
        $this->info("获取成功...");
    }
}
